/*
 * video.c
 *
 * ============================================================================
 * Copyright (c) Texas Instruments Inc 2009
 *
 * Use of this software is controlled by the terms and conditions found in the
 * license agreement under which this software has been supplied or provided.
 * ============================================================================
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//from uibuttoms
#include <xdc/std.h>
#include <ti/sdo/dmai/Buffer.h>
#include <ti/sdo/simplewidget/Jpeg.h>
//#include <xdc/std.h>

//#include <ti/sdo/ce/Engine.h>
//#include <ti/sdo/ce/osal/Memory.h>

//#include <ti/sdo/dmai/Fifo.h>
//#include <ti/sdo/dmai/Pause.h>
//#include <ti/sdo/dmai/BufTab.h>
//#include <ti/sdo/dmai/VideoStd.h>
#include <ti/sdo/dmai/BufferGfx.h>
//#include <ti/sdo/dmai/Rendezvous.h>
#include <ti/sdo/dmai/ce/Vdec.h>
#include <ti/sdo/dmai/ce/Venc.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "video.h"
#include "demo.h"
#include "stdio.h"
#include "dirent.h"
//#include "hashMap.h"
#include "sendBuff.h"

/********************
add header file by LHS
*********************/
#include "seft_struct.h"
#include "seft_util.h"
#include "ftp.h"
#include "rabbitmq.h"
#include "sw_perform.h"



//#define CAPTURE_PIPE_SIZE       2
//#define DISPLAY_PIPE_SIZE       2
//#define NUM_VIDEO_BUFS          CAPTURE_PIPE_SIZE + DISPLAY_PIPE_SIZE
#define CAPTURE_PIPE_SIZE       1
#define DISPLAY_PIPE_SIZE       0
#define NUM_VIDEO_BUFS          CAPTURE_PIPE_SIZE + DISPLAY_PIPE_SIZE
#define SOCKET			int
#define INVALID_SOCKET		-1
//#define SERVIP	    "202.127.26.182"
#define SERVIP	    "192.168.30.77"
#define SERVPORT 		80					//·�˿؍
#define MAXBACKLOG		5
/* The masks to use for knowing when a buffer is free */
#define CODEC_FREE              0x1
#define DISPLAY_FREE            0x2
#define DELAY_MS                (500)
////////////////////////////
VIDENC_InArgs   inArgs;
VIDENC_OutArgs  outArgs;
char *remote_adress = NULL;
unsigned int remote_port = 0;



#define BMP_ALIGN (4)
#define WIDTH			720
#define HEIGHT			576

/***********************************************
*	add by LHS pthread
***********************************************/
extern void *Interface(p_seft_plate_encode_t parameter);

pthread_mutex_t netInterface_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  netInterface_cond  = PTHREAD_COND_INITIALIZER;
pthread_t id_netInterface;

seft_plate_encode_t input_node;
p_seft_plate_encode_t p_input_node=&input_node;
int global_interface=0;


const unsigned char palette[256][4] = {
		0x00, 0x00, 0x00, 0x00,
		0x01, 0x01, 0x01, 0x00,
		0x02, 0x02, 0x02, 0x00,
		0x03, 0x03, 0x03, 0x00,
		0x04, 0x04, 0x04, 0x00,
		0x05, 0x05, 0x05, 0x00,
		0x06, 0x06, 0x06, 0x00,
		0x07, 0x07, 0x07, 0x00,
		0x08, 0x08, 0x08, 0x00,
		0x09, 0x09, 0x09, 0x00,
		0x0A, 0x0A, 0x0A, 0x00,
		0x0B, 0x0B, 0x0B, 0x00,
		0x0C, 0x0C, 0x0C, 0x00,
		0x0D, 0x0D, 0x0D, 0x00,
		0x0E, 0x0E, 0x0E, 0x00,
		0x0F, 0x0F, 0x0F, 0x00,
		0x10, 0x10, 0x10, 0x00,
		0x11, 0x11, 0x11, 0x00,
		0x12, 0x12, 0x12, 0x00,
		0x13, 0x13, 0x13, 0x00,
		0x14, 0x14, 0x14, 0x00,
		0x15, 0x15, 0x15, 0x00,
		0x16, 0x16, 0x16, 0x00,
		0x17, 0x17, 0x17, 0x00,
		0x18, 0x18, 0x18, 0x00,
		0x19, 0x19, 0x19, 0x00,
		0x1A, 0x1A, 0x1A, 0x00,
		0x1B, 0x1B, 0x1B, 0x00,
		0x1C, 0x1C, 0x1C, 0x00,
		0x1D, 0x1D, 0x1D, 0x00,
		0x1E, 0x1E, 0x1E, 0x00,
		0x1F, 0x1F, 0x1F, 0x00,
		0x20, 0x20, 0x20, 0x00,
		0x21, 0x21, 0x21, 0x00,
		0x22, 0x22, 0x22, 0x00,
		0x23, 0x23, 0x23, 0x00,
		0x24, 0x24, 0x24, 0x00,
		0x25, 0x25, 0x25, 0x00,
		0x26, 0x26, 0x26, 0x00,
		0x27, 0x27, 0x27, 0x00,
		0x28, 0x28, 0x28, 0x00,
		0x29, 0x29, 0x29, 0x00,
		0x2A, 0x2A, 0x2A, 0x00,
		0x2B, 0x2B, 0x2B, 0x00,
		0x2C, 0x2C, 0x2C, 0x00,
		0x2D, 0x2D, 0x2D, 0x00,
		0x2E, 0x2E, 0x2E, 0x00,
		0x2F, 0x2F, 0x2F, 0x00,
		0x30, 0x30, 0x30, 0x00,
		0x31, 0x31, 0x31, 0x00,
		0x32, 0x32, 0x32, 0x00,
		0x33, 0x33, 0x33, 0x00,
		0x34, 0x34, 0x34, 0x00,
		0x35, 0x35, 0x35, 0x00,
		0x36, 0x36, 0x36, 0x00,
		0x37, 0x37, 0x37, 0x00,
		0x38, 0x38, 0x38, 0x00,
		0x39, 0x39, 0x39, 0x00,
		0x3A, 0x3A, 0x3A, 0x00,
		0x3B, 0x3B, 0x3B, 0x00,
		0x3C, 0x3C, 0x3C, 0x00,
		0x3D, 0x3D, 0x3D, 0x00,
		0x3E, 0x3E, 0x3E, 0x00,
		0x3F, 0x3F, 0x3F, 0x00,
		0x40, 0x40, 0x40, 0x00,
		0x41, 0x41, 0x41, 0x00,
		0x42, 0x42, 0x42, 0x00,
		0x43, 0x43, 0x43, 0x00,
		0x44, 0x44, 0x44, 0x00,
		0x45, 0x45, 0x45, 0x00,
		0x46, 0x46, 0x46, 0x00,
		0x47, 0x47, 0x47, 0x00,
		0x48, 0x48, 0x48, 0x00,
		0x49, 0x49, 0x49, 0x00,
		0x4A, 0x4A, 0x4A, 0x00,
		0x4B, 0x4B, 0x4B, 0x00,
		0x4C, 0x4C, 0x4C, 0x00,
		0x4D, 0x4D, 0x4D, 0x00,
		0x4E, 0x4E, 0x4E, 0x00,
		0x4F, 0x4F, 0x4F, 0x00,
		0x50, 0x50, 0x50, 0x00,
		0x51, 0x51, 0x51, 0x00,
		0x52, 0x52, 0x52, 0x00,
		0x53, 0x53, 0x53, 0x00,
		0x54, 0x54, 0x54, 0x00,
		0x55, 0x55, 0x55, 0x00,
		0x56, 0x56, 0x56, 0x00,
		0x57, 0x57, 0x57, 0x00,
		0x58, 0x58, 0x58, 0x00,
		0x59, 0x59, 0x59, 0x00,
		0x5A, 0x5A, 0x5A, 0x00,
		0x5B, 0x5B, 0x5B, 0x00,
		0x5C, 0x5C, 0x5C, 0x00,
		0x5D, 0x5D, 0x5D, 0x00,
		0x5E, 0x5E, 0x5E, 0x00,
		0x5F, 0x5F, 0x5F, 0x00,
		0x60, 0x60, 0x60, 0x00,
		0x61, 0x61, 0x61, 0x00,
		0x62, 0x62, 0x62, 0x00,
		0x63, 0x63, 0x63, 0x00,
		0x64, 0x64, 0x64, 0x00,
		0x65, 0x65, 0x65, 0x00,
		0x66, 0x66, 0x66, 0x00,
		0x67, 0x67, 0x67, 0x00,
		0x68, 0x68, 0x68, 0x00,
		0x69, 0x69, 0x69, 0x00,
		0x6A, 0x6A, 0x6A, 0x00,
		0x6B, 0x6B, 0x6B, 0x00,
		0x6C, 0x6C, 0x6C, 0x00,
		0x6D, 0x6D, 0x6D, 0x00,
		0x6E, 0x6E, 0x6E, 0x00,
		0x6F, 0x6F, 0x6F, 0x00,
		0x70, 0x70, 0x70, 0x00,
		0x71, 0x71, 0x71, 0x00,
		0x72, 0x72, 0x72, 0x00,
		0x73, 0x73, 0x73, 0x00,
		0x74, 0x74, 0x74, 0x00,
		0x75, 0x75, 0x75, 0x00,
		0x76, 0x76, 0x76, 0x00,
		0x77, 0x77, 0x77, 0x00,
		0x78, 0x78, 0x78, 0x00,
		0x79, 0x79, 0x79, 0x00,
		0x7A, 0x7A, 0x7A, 0x00,
		0x7B, 0x7B, 0x7B, 0x00,
		0x7C, 0x7C, 0x7C, 0x00,
		0x7D, 0x7D, 0x7D, 0x00,
		0x7E, 0x7E, 0x7E, 0x00,
		0x7F, 0x7F, 0x7F, 0x00,
		0x80, 0x80, 0x80, 0x00,
		0x81, 0x81, 0x81, 0x00,
		0x82, 0x82, 0x82, 0x00,
		0x83, 0x83, 0x83, 0x00,
		0x84, 0x84, 0x84, 0x00,
		0x85, 0x85, 0x85, 0x00,
		0x86, 0x86, 0x86, 0x00,
		0x87, 0x87, 0x87, 0x00,
		0x88, 0x88, 0x88, 0x00,
		0x89, 0x89, 0x89, 0x00,
		0x8A, 0x8A, 0x8A, 0x00,
		0x8B, 0x8B, 0x8B, 0x00,
		0x8C, 0x8C, 0x8C, 0x00,
		0x8D, 0x8D, 0x8D, 0x00,
		0x8E, 0x8E, 0x8E, 0x00,
		0x8F, 0x8F, 0x8F, 0x00,
		0x90, 0x90, 0x90, 0x00,
		0x91, 0x91, 0x91, 0x00,
		0x92, 0x92, 0x92, 0x00,
		0x93, 0x93, 0x93, 0x00,
		0x94, 0x94, 0x94, 0x00,
		0x95, 0x95, 0x95, 0x00,
		0x96, 0x96, 0x96, 0x00,
		0x97, 0x97, 0x97, 0x00,
		0x98, 0x98, 0x98, 0x00,
		0x99, 0x99, 0x99, 0x00,
		0x9A, 0x9A, 0x9A, 0x00,
		0x9B, 0x9B, 0x9B, 0x00,
		0x9C, 0x9C, 0x9C, 0x00,
		0x9D, 0x9D, 0x9D, 0x00,
		0x9E, 0x9E, 0x9E, 0x00,
		0x9F, 0x9F, 0x9F, 0x00,
		0xA0, 0xA0, 0xA0, 0x00,
		0xA1, 0xA1, 0xA1, 0x00,
		0xA2, 0xA2, 0xA2, 0x00,
		0xA3, 0xA3, 0xA3, 0x00,
		0xA4, 0xA4, 0xA4, 0x00,
		0xA5, 0xA5, 0xA5, 0x00,
		0xA6, 0xA6, 0xA6, 0x00,
		0xA7, 0xA7, 0xA7, 0x00,
		0xA8, 0xA8, 0xA8, 0x00,
		0xA9, 0xA9, 0xA9, 0x00,
		0xAA, 0xAA, 0xAA, 0x00,
		0xAB, 0xAB, 0xAB, 0x00,
		0xAC, 0xAC, 0xAC, 0x00,
		0xAD, 0xAD, 0xAD, 0x00,
		0xAE, 0xAE, 0xAE, 0x00,
		0xAF, 0xAF, 0xAF, 0x00,
		0xB0, 0xB0, 0xB0, 0x00,
		0xB1, 0xB1, 0xB1, 0x00,
		0xB2, 0xB2, 0xB2, 0x00,
		0xB3, 0xB3, 0xB3, 0x00,
		0xB4, 0xB4, 0xB4, 0x00,
		0xB5, 0xB5, 0xB5, 0x00,
		0xB6, 0xB6, 0xB6, 0x00,
		0xB7, 0xB7, 0xB7, 0x00,
		0xB8, 0xB8, 0xB8, 0x00,
		0xB9, 0xB9, 0xB9, 0x00,
		0xBA, 0xBA, 0xBA, 0x00,
		0xBB, 0xBB, 0xBB, 0x00,
		0xBC, 0xBC, 0xBC, 0x00,
		0xBD, 0xBD, 0xBD, 0x00,
		0xBE, 0xBE, 0xBE, 0x00,
		0xBF, 0xBF, 0xBF, 0x00,
		0xC0, 0xC0, 0xC0, 0x00,
		0xC1, 0xC1, 0xC1, 0x00,
		0xC2, 0xC2, 0xC2, 0x00,
		0xC3, 0xC3, 0xC3, 0x00,
		0xC4, 0xC4, 0xC4, 0x00,
		0xC5, 0xC5, 0xC5, 0x00,
		0xC6, 0xC6, 0xC6, 0x00,
		0xC7, 0xC7, 0xC7, 0x00,
		0xC8, 0xC8, 0xC8, 0x00,
		0xC9, 0xC9, 0xC9, 0x00,
		0xCA, 0xCA, 0xCA, 0x00,
		0xCB, 0xCB, 0xCB, 0x00,
		0xCC, 0xCC, 0xCC, 0x00,
		0xCD, 0xCD, 0xCD, 0x00,
		0xCE, 0xCE, 0xCE, 0x00,
		0xCF, 0xCF, 0xCF, 0x00,
		0xD0, 0xD0, 0xD0, 0x00,
		0xD1, 0xD1, 0xD1, 0x00,
		0xD2, 0xD2, 0xD2, 0x00,
		0xD3, 0xD3, 0xD3, 0x00,
		0xD4, 0xD4, 0xD4, 0x00,
		0xD5, 0xD5, 0xD5, 0x00,
		0xD6, 0xD6, 0xD6, 0x00,
		0xD7, 0xD7, 0xD7, 0x00,
		0xD8, 0xD8, 0xD8, 0x00,
		0xD9, 0xD9, 0xD9, 0x00,
		0xDA, 0xDA, 0xDA, 0x00,
		0xDB, 0xDB, 0xDB, 0x00,
		0xDC, 0xDC, 0xDC, 0x00,
		0xDD, 0xDD, 0xDD, 0x00,
		0xDE, 0xDE, 0xDE, 0x00,
		0xDF, 0xDF, 0xDF, 0x00,
		0xE0, 0xE0, 0xE0, 0x00,
		0xE1, 0xE1, 0xE1, 0x00,
		0xE2, 0xE2, 0xE2, 0x00,
		0xE3, 0xE3, 0xE3, 0x00,
		0xE4, 0xE4, 0xE4, 0x00,
		0xE5, 0xE5, 0xE5, 0x00,
		0xE6, 0xE6, 0xE6, 0x00,
		0xE7, 0xE7, 0xE7, 0x00,
		0xE8, 0xE8, 0xE8, 0x00,
		0xE9, 0xE9, 0xE9, 0x00,
		0xEA, 0xEA, 0xEA, 0x00,
		0xEB, 0xEB, 0xEB, 0x00,
		0xEC, 0xEC, 0xEC, 0x00,
		0xED, 0xED, 0xED, 0x00,
		0xEE, 0xEE, 0xEE, 0x00,
		0xEF, 0xEF, 0xEF, 0x00,
		0xF0, 0xF0, 0xF0, 0x00,
		0xF1, 0xF1, 0xF1, 0x00,
		0xF2, 0xF2, 0xF2, 0x00,
		0xF3, 0xF3, 0xF3, 0x00,
		0xF4, 0xF4, 0xF4, 0x00,
		0xF5, 0xF5, 0xF5, 0x00,
		0xF6, 0xF6, 0xF6, 0x00,
		0xF7, 0xF7, 0xF7, 0x00,
		0xF8, 0xF8, 0xF8, 0x00,
		0xF9, 0xF9, 0xF9, 0x00,
		0xFA, 0xFA, 0xFA, 0x00,
		0xFB, 0xFB, 0xFB, 0x00,
		0xFC, 0xFC, 0xFC, 0x00,
		0xFD, 0xFD, 0xFD, 0x00,
		0xFE, 0xFE, 0xFE, 0x00,
		0xFF, 0xFF, 0xFF, 0x00,
};

typedef struct
{
	char type1;
	char type2;
}BmpFileHead;

typedef struct
{
    unsigned int imageSize;
    unsigned int blank;
    unsigned int startPosition;
    unsigned int    length;
    unsigned int    width;
    unsigned int    height;
    unsigned short    colorPlane;
    unsigned short    bitColor;
    unsigned int    zipFormat;
    unsigned int    realSize;
    unsigned int    xPels;
    unsigned int    yPels;
    unsigned int    colorUse;
    unsigned int    colorImportant;
}BmpInfoHead;

int cvSaveImageSize(const int imgWidth,const int imgHeight,const int channels)
{
    int size = 0;
	int step = imgWidth * channels; //windows位图step必须是4的倍数
	int modbyte = step & (BMP_ALIGN - 1); //
	if (modbyte != 0)
		step += (BMP_ALIGN - modbyte);
    size += sizeof(BmpFileHead);
    size += sizeof(BmpInfoHead);
    if(channels==1)
        size += sizeof(palette);
    size += step * imgHeight;
    return size;
}

int cvSaveImageInAddr0(char* pdst, char* imgData,const int imgWidth, const int imgHeight, const int imgWidthStep, const int channels)
{
//	printf("enter cvSaveImageInAddr0\n");
	char *addr = pdst;
	BmpFileHead bmpfilehead = {'B','M'};
	BmpInfoHead bmpinfohead;
    int write_num = 0;
	int step = imgWidth * channels; //windows位图step必须是4的倍数
	int modbyte = step & (BMP_ALIGN - 1); //
	if (modbyte != 0)
		step += (BMP_ALIGN - modbyte);

    memcpy(addr,&bmpfilehead,sizeof(BmpFileHead));
	addr += sizeof(BmpFileHead);//move to next section

	bmpinfohead.blank = 0;
	bmpinfohead.startPosition = sizeof(BmpFileHead) + sizeof(BmpInfoHead);
	bmpinfohead.realSize = step * imgHeight;
	bmpinfohead.imageSize = bmpinfohead.realSize + bmpinfohead.startPosition;
	bmpinfohead.length = 0x28;
	bmpinfohead.width = imgWidth;
	bmpinfohead.height= imgHeight;
	bmpinfohead.colorPlane = 0x01;
	bmpinfohead.bitColor = 8 * channels;
	bmpinfohead.zipFormat = 0;
	bmpinfohead.xPels = 0xEC4;
	bmpinfohead.yPels = 0xEC4;
	bmpinfohead.colorUse = 0;
	bmpinfohead.colorImportant = 0;
	if(channels == 1)//Gray Image-->write palette
	{
		bmpinfohead.startPosition += sizeof(palette);
		bmpinfohead.imageSize += sizeof(palette);
		memcpy(addr,&bmpinfohead, sizeof(BmpInfoHead));
		addr += sizeof(BmpInfoHead);//move to next section
		memcpy(addr,&palette[0][0],sizeof(palette));
		addr += sizeof(palette);//move to next section
	}
	else
	{
		memcpy(addr,&bmpinfohead, sizeof(BmpInfoHead));
		addr += sizeof(BmpInfoHead);//move to next section
	}
	char *pdata = imgData + (imgHeight - 1) * imgWidthStep;

	int idx;
	for(idx = imgHeight - 1; idx >= 0 ; idx--)
	{
		memcpy(addr,pdata, step);
		addr += step;//move to next section
		pdata -= imgWidthStep;
	}
//	FILE* p = fopen("test.bmp", "wb+");
//	fwrite(pdst,1,bmpinfohead.imageSize,p);
//	fclose(p);
//	printf("leave cvSaveImageInAddr0\n");
	return 0;
}

static int fileTypeEq(char *filename, char* destname)
{
	int pointLoc = strlen(filename);
	while(filename[--pointLoc] != '.');
	if(strcmp(filename + pointLoc + 1,destname)==0)
	{
		return 0;
	}
	else
	{
		return -1;
	}
}

static char *getBaseName(char *filename)
{
	int pointLoc = strlen(filename);
    if(filename[pointLoc - 1] == '/')
        pointLoc--;//ignore last '/'
	while(filename[--pointLoc] != '/')//find the last '/' backward
    {
        if(pointLoc < 0)
            break;
    }
    //printf("Loc:%d\n",pointLoc);
    return filename + pointLoc + 1;
}

static char * getCarColorFromIndex(int a)
{
    char *colorIndex[] =
    {
        {"Black"},
        {"Blue"},
        {"Brown"},
        {"Cyan"},
        {"Gray"},
        {"Green"},
        {"Red"},
        {"Silver"},
        {"White"},
        {"Yellow"},
        {"Purple or else"}
    };
    if(a > sizeof(colorIndex)/sizeof(colorIndex[0]) || a < 0)
        return NULL;
    else 
        return colorIndex[a];
}

SOCKET NetServerCreate() 
{
	SOCKET socketServer = INVALID_SOCKET;
	SOCKET socketClient = INVALID_SOCKET;

	//socket
	if ((socketServer = socket(AF_INET, SOCK_STREAM/*SOCK_DGRAM*/, 0))
			== INVALID_SOCKET) {
		printf("socket error\n");
		goto error;
	}

	//bind
	struct sockaddr_in socketAddr_in;
	socketAddr_in.sin_family = AF_INET;
	socketAddr_in.sin_addr.s_addr = 0;
	//socketAddr_in.sin_port = htons(SERVPORT);
	socketAddr_in.sin_port = htons(remote_port);
	if (bind(socketServer, (struct sockaddr*) &socketAddr_in,
			sizeof(socketAddr_in)) > 0) {
		printf("bind error\n");
		goto error;
	}

	//listen
	if (listen(socketServer, MAXBACKLOG) < 0) {
		printf("listen error\n");
		close(socketServer);
		socketServer = INVALID_SOCKET;
		goto error;
	}

	struct sockaddr_in socketAddrIn;
	socklen_t addrSize = sizeof(socketAddrIn);
	socketClient = accept(socketServer, (struct sockaddr*) &socketAddrIn,
			&addrSize);
	if (socketClient == INVALID_SOCKET) {
		printf("accept error,break!\n");
		goto error;
	}
	printf("accept: %s socket %d\n", inet_ntoa(socketAddrIn.sin_addr),
			socketClient);
	return socketClient;
	error: if (socketServer != INVALID_SOCKET)
		close(socketServer);
	socketClient = INVALID_SOCKET;
	return socketClient;
}

SOCKET NetInit( )
{
	SOCKET socketClient = INVALID_SOCKET;

	//socket
	if ((socketClient = socket(AF_INET, SOCK_STREAM/*SOCK_DGRAM*/, 0))
			== INVALID_SOCKET) {
		printf("socket error\n");
		goto error;
	}

	//bind
    printf("remote adress:%s:%d\n",remote_adress,remote_port);
	struct sockaddr_in remote_addr;
	remote_addr.sin_family = AF_INET;
	//remote_addr.sin_addr.s_addr = inet_addr(SERVIP);
	remote_addr.sin_addr.s_addr = inet_addr(remote_adress);
	//remote_addr.sin_port = htons(SERVPORT);
	remote_addr.sin_port = htons(remote_port);
	if (connect(socketClient, (struct sockaddr *) &remote_addr,
			sizeof(struct sockaddr)) < 0) {
		printf("connect failed!\n");
		goto error;
	}
    printf("============connected to server OK===========\n");
	return socketClient;
	error: if (socketClient != INVALID_SOCKET)
		close(socketClient);
	socketClient = INVALID_SOCKET;
	return socketClient;
}

int NetSend(SOCKET socket, void *buf, int len, int flag) {
	fd_set fdR;
	struct timeval timeout;
	int ret = SUCCESS;
	int total = 0;

	//printf("enter NetSend!\n");
	timeout.tv_sec = 3;
	timeout.tv_usec = 0;

	FD_ZERO(&fdR);
	FD_SET(socket, &fdR);
	switch (select(socket + 1, NULL, &fdR, NULL, &timeout)) {
	case -1:
		printf("send select: connect error!\n");
		ret = FAILURE;
		break;
	case 0:
		printf("send select: time out!\n");
		ret = FAILURE;
		break;
	default:
		if (FD_ISSET(socket, &fdR)) {
			ret = send(socket, (const char*) buf, len, flag);
			if (ret != len) {
				printf("send %d character, error!\n", ret);
				ret = FAILURE;
			} else {
				total = ret;
				printf("send %d character finished!\n", ret);
			}
		}
	}

	return ret;
}
/******************************************************************************
 * encodedecode
 ******************************************************************************/
//static Int encodedecode(Venc_Handle hVe, Vdec_Handle hVd,
//Buffer_Handle hVidBuf, Buffer_Handle hEncBuf, Buffer_Handle hOutBuf, Fifo_Handle displayFifo)
static Int encodedecode(Venc_Handle hVe, Vdec_Handle hVd,
Buffer_Handle hVidBuf, Buffer_Handle hEncBuf, Fifo_Handle displayFifo, char *dirfile)
{
    //char dirfile[] = "/home/testJpeg";
    DIR *p_dir;// = opendir(dirfile);
    struct dirent *p_dirent;
    int totalImageNum = 0;
    int rightImageNum = 0;
    int errImageNum = 0;
    int unkownImageNum = 0;
    char outMesgPath[80] = "/mnt/yaffs/"; 
    //FILE *pResult;
	SOCKET socketClient = INVALID_SOCKET;
 	NET_SEND_BUFF sendBuf;
	time_t time_now;
	struct tm *tm_local;
 	int tempI = 0;

/******************************************************
*	add by LHS
*******************************************************/
	// the follow variant is define in the function videoThrFxn as critical section global variant in this file      
	// seft_plate_encode_t input_node;
	// p_seft_plate_encode_t p_input_node=&input_node;
	 char eventID[250];
	 char shortedTime[35];
	 struct tm ptime;
       char relativePath[30];
	memset(p_input_node,0,sizeof(seft_plate_encode_t));

	if(pthread_create(&id_netInterface,NULL,Interface,p_input_node))
	  printf("fail to create the netInterface\n");	



    
       time_now = time((time_t *)0);
	tm_local = localtime(&time_now);
	strcpy(sendBuf.time_now,asctime(tm_local));//current time
	printf("%s\n",sendBuf.time_now);

	sendBuf.speed = 0;//speed-read usb device - 0
    //sendBuf.connect_state = 0;//set connect to server
    printf("dirfile = %s\n",dirfile); 
    tempI = strlen(dirfile);
    if(dirfile[tempI - 1] == '/')
        dirfile[tempI - 1] = '\0';//delete the last /
    strcat(outMesgPath,getBaseName(dirfile));
    strcat(outMesgPath,".txt");
    printf("=======>Result file:%s <========\n",outMesgPath);
    //pResult = fopen(outMesgPath,"w+");
    //if(pResult == NULL)
    //{
    //    printf("create file %s failed.\n",outMesgPath);
    //    exit(-1);
    //}

    /* Make sure the whole buffer is used for input and output */
    BufferGfx_resetDimensions(hVidBuf);

    Buffer_Attrs testAttrs = Buffer_Attrs_DEFAULT;
    testAttrs.type = Buffer_Type_GRAPHICS;
    //if (Venc_process(hVe, hVidBuf, hEncBuf) < 0) {
    //    ERR("Failed to encode video buffer\n");
    //    return FAILURE;
    //}
    printf("the directory %s will be analysing.\n",dirfile);
    p_dir = opendir(dirfile);
    if(p_dir == NULL)
	printf("encodedecode open %s fail.\n",dirfile);

//    socketClient = NetServerCreate(); 
	socketClient = NetInit();
	if (socketClient == INVALID_SOCKET) 
    {
        printf("unable to connect to server %s.\n",remote_adress);
        
    }

	Buffer_Handle testBufferIn;
    Buffer_Handle testBufferOut;
    const int BuffInMaxSize = 1400*1024*3;//=4300800,max=4500000
    testBufferIn = Buffer_create((Int32)(BuffInMaxSize),&testAttrs);//in bmp
	if(testBufferIn == NULL)
	{
	    printf("testBufferIn(int) = 0x%x.\n",(int)testBufferIn);
	}
    testBufferOut = Buffer_create((Int32)(720*2), &testAttrs);
	if(testBufferOut == NULL)
	{
        printf("testBufferOut(int) = 0x%x.\n",(int)testBufferOut);
	}
    while(p_dirent = readdir(p_dir))
    {
        //printf("开始处理\n");
        char filename[80];
        //char dstName[80];
        FILE *pfile;
        int fileSize;
        int readSize;
        //Int8 *pBufOut;

        memset(filename,'\0',sizeof(filename));
        //memset(dstName,'\0',sizeof(dstName));
        if(strlen(p_dirent->d_name) < 3)continue;//omit . and ..
        totalImageNum++;
        strcpy(filename,dirfile);
        strcat(filename,"/");
        strcat(filename,p_dirent->d_name);
        //strcpy(dstName,"/home/");
        //strcat(dstName,p_dirent->d_name);
        printf("#####Start analysing <%s>======>\n",filename);
	    pfile = fopen(filename,"rb");
	    if(pfile == NULL)
	    	printf("encodedecode open %s fail.\n",filename);
	    fseek(pfile,0L,SEEK_END);
	    fileSize = ftell(pfile);
	    fseek(pfile,0L,SEEK_SET);
	    printf("File %s size : %d.\n",filename,fileSize);
	    char *pImageData = (char*)malloc(fileSize*sizeof(char));
	    if(pImageData == NULL)
    	{
    		printf("malloc filesize err.\n");
            fclose(pfile);
    		exit(-1);
    	}
    	readSize = fread(pImageData,1,fileSize,pfile);
    	if(readSize != fileSize)
    	{
    		printf("fread err, read sieze is %d.\n",readSize);
            fclose(pfile);
            free(pImageData);
    		continue;
    	}

        if(fileTypeEq(p_dirent->d_name,"BMP") == 0 || fileTypeEq(p_dirent->d_name,"bmp") == 0)//bmp file
	    {        
            printf("the input file type is <BMP>.\n");
		    /*testBufferIn = Buffer_create((Int32)(fileSize),&testAttrs);//in bmp
		    if(testBufferIn == NULL)
		    {
		        printf("testBufferIn(int) = 0x%x.\n",(int)testBufferIn);
		    }
		    */
		    //printf("numBufs of testBufferIn %d,testBufferOut %d\n",(int)Buffer_getSize(testBufferIn),(int)Buffer_getSize(testBufferOut));//Buffer_getSize(hEncBuf));//
		    Buffer_setNumBytesUsed(testBufferIn,0);
		    //readSize = fread(Buffer_getUserPtr(testBufferIn),1,fileSize,pfile);
		    memcpy(Buffer_getUserPtr(testBufferIn),pImageData,fileSize);//copy data
		    Buffer_setNumBytesUsed(testBufferIn,readSize);
        }
        else if(fileTypeEq(p_dirent->d_name,"JPG") == 0 || fileTypeEq(p_dirent->d_name,"jpg") == 0 ||
		fileTypeEq(p_dirent->d_name,"JPEG") == 0 || fileTypeEq(p_dirent->d_name,"jpeg") == 0)//jpg file
    	{
            printf("the input file type is <JPG>.\n");
    		Jpeg_Handle hJpeg = Jpeg_create(filename);
    		if(hJpeg != NULL)
    		    printf("Jpeg width=%d,height=%d\n",hJpeg->w,hJpeg->h);
            else
            {
                printf("create jpeg handle err.\n");
                free(pImageData);
                fclose(pfile);
                continue ;
            }
		    //memcpy(Buffer_getUserPtr(testBufferIn),hJpeg->bufp,hJpeg->w*hJpeg->h);
		
		    int bmpFileSize = cvSaveImageSize(hJpeg->w,hJpeg->h,3);
		    printf("Load Bmp filesize = %d\n",bmpFileSize);
		    /*testBufferIn = Buffer_create((Int32)(bmpFileSize),&testAttrs);//in bmp
		    if(testBufferIn == NULL)
		    {
		        printf("testBufferIn(int) = 0x%x.\n",(int)testBufferIn);
		    }
		    */
		    //printf("numBufs of testBufferIn %d,testBufferOut %d\n",(int)Buffer_getSize(testBufferIn),(int)Buffer_getSize(testBufferOut));//Buffer_getSize(hEncBuf));//
		    Buffer_setNumBytesUsed(testBufferIn,0);
		
		    cvSaveImageInAddr0(Buffer_getUserPtr(testBufferIn),hJpeg->bufp,hJpeg->w,hJpeg->h,hJpeg->w*3,3);
		    Buffer_setNumBytesUsed(testBufferIn,bmpFileSize);
		    Jpeg_delete(hJpeg);
	    }	
        else
        {
            printf("the input file type is not supported.\n");
            fclose(pfile);
            //Buffer_delete(testBufferIn);
            free(pImageData);
            continue;
        }
        printf("Enter DSP program.\n");
/***************************************************************
The kernel function.
***************************************************************/	
		if (Venc_process(hVe, testBufferIn,testBufferOut) < 0) 
		{
        ERR("Failed to encode video buffer\n");
        return FAILURE;
		}
      printf("x=%d,y=%d,w=%d,h=%d\n",outArgs.plateInfo.rect.x,outArgs.plateInfo.rect.y,outArgs.plateInfo.rect.width,outArgs.plateInfo.rect.height);
      printf("[dsp runtime %dms ]\n",(int)(outArgs.plateInfo.runTime * 1000));
      if(socketClient != INVALID_SOCKET) 
	 {
		int len = fileSize;
		int ret = NetSend(socketClient, &len, sizeof(len), 0);
		if (ret == sizeof(len))
		{
			ret = NetSend(socketClient, pImageData, len, 0);
			if (ret != len)
				printf("send video buf error!\n");
		} else
			printf("send video len error!\n");
		memcpy(&sendBuf.plateInfo,&outArgs.plateInfo,sizeof(TRIMPS_PLATE));
        time_now = time((time_t *)0);
/***********************************************************************************
input parameter:time_now
************************************************************************************/		
        tm_local = localtime(&time_now);
        strcpy(sendBuf.time_now,asctime(tm_local));//current time
        printf("%s\n",sendBuf.time_now);
        sendBuf.speed = 0;//speed-read usb device - 0
        len = sizeof(NET_SEND_BUFF);
        printf("ROI:%d,%d,%d,%d\n",sendBuf.plateInfo.rect.x,sendBuf.plateInfo.rect.y,sendBuf.plateInfo.rect.width,sendBuf.plateInfo.rect.height);
        //printf("DSP-width:%d,DSP-height%d\n",outArgs.plateInfo.imgWidth,outArgs.plateInfo.imgHeight);
/****************************************************
*	my program start.
****************************************************/
/*****************************************************************************************
*	add by LHS pthread
*****************************************************************************************/
             pthread_mutex_lock(&netInterface_mutex);//add by LHS				
            //inital the input parameters by LHS.


		memset(p_input_node,0,sizeof(seft_plate_encode_t));
		global_interface++;

		//set the flag of the image by LHS.
		p_input_node->plate_upload_pend=seft_image_exist;
		p_input_node->scene_upload_pend=seft_image_not_exist;

            //get the time info by LHS
		p_input_node->time=time_now;              //input parameter[time ]
                
		//set the speed of the target
		//(p_input_node->msg).speed = sendBuf.speed;//input parameter[speed]
		(p_input_node->msg).speed = 20+rand()%50;

		
		(p_input_node->msg).plateNumberColor = sendBuf.plateInfo.color;//input parameter[color]

		strcpy((p_input_node->msg).terminalID,"SD04");//input parameter[terminalID:SD01 or HD01]

		strcpy((p_input_node->msg).panoramaName,"2");

               //set the vehiclePicName 
            const char *picName=(const char*)(strrchr(filename,'/')+1);
 		strcpy((p_input_node->msg).vehiclePicName,picName);
	
		sprintf(eventID,"e_%s",picName);
		strcpy((p_input_node->msg).eventID,eventID);

            localtime_r(&(p_input_node->time),&ptime);

		sprintf(shortedTime,"%d-%d-%dT%d:%d:%d.2600000+08.00",ptime.tm_year+1900,ptime.tm_mon+1,ptime.tm_mday,ptime.tm_hour,ptime.tm_min,ptime.tm_sec);
		strcpy((p_input_node->msg).shortedTime,shortedTime);
           //set relativePath

		sprintf(relativePath,"%s/%d/%02d/%02d/%02d/%02d/",(p_input_node->msg).terminalID,ptime.tm_year+1900,ptime.tm_mon+1,ptime.tm_mday,ptime.tm_hour,ptime.tm_min);

		strcpy((p_input_node->msg).relativePath,relativePath);

		printf("(p_input_node->msg).terminalID============================>%s\n",(p_input_node->msg).terminalID);
		strcpy((p_input_node->msg).plateNumber,sendBuf.plateInfo.number);//input parameter[plateNumber]
	
		//printf("*************************************** %s\n",dirfile);
	
		strcpy(p_input_node->plate_pathname,filename);
		
		printf("************************************************enter my program\n");
/*****************************************************************************************
*	add by LHS pthread
*****************************************************************************************/
                if(global_interface==1)
		    {
			pthread_cond_signal(&netInterface_cond);
			printf("signal successfully\n");
		    }
		   else
		    {
			printf("**************************pthread signal fail\n");
		    }
               
               pthread_mutex_unlock(&netInterface_mutex);
		
#if 0
             struct timeval first,second;
		float timeuse;
		gettimeofday(&first,NULL);

#endif
		//seft_sem_writer_perform(&input_node);
//	

#if 0
		gettimeofday(&second,NULL);
		timeuse=(second.tv_sec-first.tv_sec)*1000000+second.tv_usec-first.tv_usec;
		timeuse/=1000000;
		printf("==============================%f==========================\n",timeuse);

#endif



                


		//strcpy(p_input_node->scene_pathname,"./scene.jpg");

		//strcpy(p_input_node->ttl_pathname,"./tt1.jpg");	
		
		ret = NetSend(socketClient, &len, sizeof(len), 0);
		if (ret == sizeof(len)) 
		{
			ret = NetSend(socketClient, &sendBuf,len, 0);
			if (ret != len)
				printf("send number buf error!\n");
		} else
			printf("send number len error!\n");
	 }
 
	    free(pImageData);
	    fclose(pfile);
        if(outArgs.plateInfo.flag == 1)
        {
            //fprintf(pResult,"Source picture No.%d %s\nNumber is:%s\n",totalImageNum,filename,outArgs.plateInfo.number);
            //fprintf(pResult,"Car Color is %s.\n",getCarColorFromIndex(outArgs.plateInfo.singleOrDouble));
        }
        else
        {
            unkownImageNum++;
            //fprintf(pResult,"Source picture No.%d %s\n Location fail.\n",totalImageNum,filename);
            printf("Plate Recognition Failure.\n");
        }
 
        printf("Venc_process() executed over.\n");
        usleep(DELAY_MS * 1000);
        //Buffer_delete(testBufferIn);
        //printf("Buffer in have been deleted.\n");
    }
    //send End connnect message
    if(socketClient != INVALID_SOCKET) 
	  {
		const char endSend[] = "disconnect tcp";
        int len = strlen(endSend) + 1;
		int ret = NetSend(socketClient, &len, sizeof(len), 0);
		if (ret == sizeof(len))
		{
			ret = NetSend(socketClient, endSend, len, 0);
			if (ret != len)
				printf("send video buf error!\n");
		} else
			printf("send video len error!\n");
	 }
 

    Buffer_delete(testBufferIn);
    Buffer_delete(testBufferOut );
    //fclose(pResult);
    close(socketClient);
	socketClient = INVALID_SOCKET;

    printf("Analysis of %s finished.\n",dirfile);
    return SUCCESS;
}

/******************************************************************************
 * videoThrFxn
 ******************************************************************************/
Void *videoThrFxn(Void *arg)
{
    VideoEnv               *envp                 = (VideoEnv *) arg;
    Void                   *status               = THREAD_SUCCESS;
    VIDDEC_Params          defaultDecParams     = Vdec_Params_DEFAULT;
    VIDDEC_DynamicParams   defaultDecDynParams  = Vdec_DynamicParams_DEFAULT;
    VIDENC_Params          defaultEncParams     = Venc_Params_DEFAULT;
    VIDENC_DynamicParams   defaultEncDynParams  = Venc_DynamicParams_DEFAULT;
    BufferGfx_Attrs         gfxAttrs             = BufferGfx_Attrs_DEFAULT;
    BufferGfx_Attrs         outAttrs             = BufferGfx_Attrs_DEFAULT;
    Buffer_Attrs            bAttrs               = Buffer_Attrs_DEFAULT;
    Vdec_Handle            hVd                 = NULL;
    Venc_Handle            hVe                 = NULL;
    BufTab_Handle           hBufTab              = NULL;
    Engine_Handle           hEngine              = NULL;
    Buffer_Handle           hEncBuf              = NULL;
    Buffer_Handle           hOutBuf              = NULL;
    Int                     ret                  = Dmai_EOK;
    Int                     numBufs              = 0;
    Buffer_Handle           hVidBuf, hDstBuf;
    VIDDEC_Params         *decParams;
    VIDDEC_DynamicParams  *decDynParams;
    VIDENC_Params         *encParams;
    VIDENC_DynamicParams  *encDynParams;
    Int32                   bufSize;
    Int                     fifoRet;
    Int 
                    bufIdx;




    char *dirName = envp->dirName;
    //printf("dirName = %s.\n",dirName);
    remote_adress = envp->remote_adress;
    remote_port = envp->remote_port;
    
    /* Use supplied params if any, otherwise use defaults */
    decParams = envp->decParams ? envp->decParams : &defaultDecParams;
    decDynParams = envp->decDynParams ? envp->decDynParams :
                                        &defaultDecDynParams;

    encParams = envp->encParams ? envp->encParams : &defaultEncParams;
    encDynParams = envp->encDynParams ? envp->encDynParams :
                                        &defaultEncDynParams;

    gblSetImageWidth(envp->imageWidth);
    gblSetImageHeight(envp->imageHeight);

    gfxAttrs.colorSpace     = ColorSpace_UYVY;
    gfxAttrs.dim.width      = envp->imageWidth;
    gfxAttrs.dim.height     = envp->imageHeight;
    gfxAttrs.dim.lineLength = BufferGfx_calcLineLength(gfxAttrs.dim.width,
                                                       gfxAttrs.colorSpace);
                                                       
    outAttrs.colorSpace     = ColorSpace_UYVY;
    outAttrs.dim.width      = envp->imageWidth;
    outAttrs.dim.height     = envp->imageHeight;
    outAttrs.dim.lineLength = BufferGfx_calcLineLength(outAttrs.dim.width,
                                                       outAttrs.colorSpace);
    outAttrs.bAttrs.useMask = DISPLAY_FREE;

    if (envp->passThrough) {
        bufSize = gfxAttrs.dim.lineLength * gfxAttrs.dim.height;

        /* Only the display thread can own a buffer since no codecs are used */
        gfxAttrs.bAttrs.useMask = DISPLAY_FREE;
    }
    else {
        /* Open the codec engine */
        printf("Engine_open\n");
        hEngine = Engine_open(envp->engineName, NULL, NULL);

        if (hEngine == NULL) {
            ERR("Failed to open codec engine %s\n", envp->engineName);
            cleanup(THREAD_FAILURE);
        }
        else
        	printf("Successed to open codec engine %s\n", envp->engineName);

        /* Set the resolution to match the specified resolution */
        encParams->maxWidth          = envp->imageWidth;
        encParams->maxHeight         = envp->imageHeight;
        encParams->inputChromaFormat = XDM_YUV_422ILE;

        /* Set up codec parameters depending on bit rate */
        if (envp->videoBitRate < 0) {
            /* Variable bit rate */
            encParams->rateControlPreset = IVIDEO_NONE;

            /*
             * If variable bit rate use a bogus bit rate value (> 0)
             * since it will be ignored.
             */
            encParams->maxBitRate        = 2000000;
        }
        else {
            /* Constant bit rate */
            encParams->rateControlPreset = IVIDEO_LOW_DELAY;
            encParams->maxBitRate        = envp->videoBitRate;
        }

        encDynParams->targetBitRate = encParams->maxBitRate;
        encDynParams->inputWidth    = encParams->maxWidth;
        encDynParams->inputHeight   = encParams->maxHeight;

        /* Create the video encoder */
        hVe = Venc_create(hEngine, envp->videoEncoder,
                            encParams, encDynParams);
        if (hVe == NULL) {
            ERR("Failed to create video encoder: %s\n", envp->videoEncoder);
            cleanup(THREAD_FAILURE);
        }

        decParams->maxWidth          = encParams->maxWidth;
        decParams->maxHeight         = encParams->maxHeight;
        decParams->forceChromaFormat = XDM_YUV_422ILE;

        /* Which output buffer size does the codec require? */
        bufSize = Venc_getInBufSize(hVe);

        /* Allocate buffer for encoded data */
       // hEncBuf = Buffer_create(bufSize, &bAttrs);
        
        /* Allocate buffer for encoded data */
        //hOutBuf = Buffer_create(bufSize, BufferGfx_getBufferAttrs(&outAttrs));

       // if (hEncBuf == NULL) {
       //     ERR("Failed to allocate buffer for encoded data\n");
       //     cleanup(THREAD_FAILURE);
       // }

        /* A buffer can be owned by either the codec or the display thread */
        gfxAttrs.bAttrs.useMask = CODEC_FREE | DISPLAY_FREE;
    }

    /* Allocate video buffers */
    hBufTab = BufTab_create(NUM_VIDEO_BUFS, bufSize,
                            BufferGfx_getBufferAttrs(&gfxAttrs));

    if (hBufTab == NULL) {
        ERR("Failed to create BufTab for display pipe\n");
        cleanup(THREAD_FAILURE);
    }

    /* Prime the capture pipe with buffers */
    for (bufIdx = 0; bufIdx < NUM_VIDEO_BUFS; bufIdx++) {
        hDstBuf = BufTab_getFreeBuf(hBufTab);

        if (hDstBuf == NULL) {
            ERR("Failed to get free buffer from BufTab\n");
            BufTab_print(hBufTab);
            cleanup(THREAD_FAILURE);
        }

        if (Fifo_put(envp->hCaptureInFifo, hDstBuf) < 0) {
            ERR("Failed to send buffer to display thread\n");
            cleanup(THREAD_FAILURE);
        }
    }

    /* Make sure the display thread is stopped when it's unlocked */
    //Pause_on(envp->hPausePrime);

    /* Signal that initialization is done and wait for other threads */
    Rendezvous_meet(envp->hRendezvousInit);

    /* Process one buffer to figure out buffer requirements */
    fifoRet = Fifo_get(envp->hCaptureOutFifo, &hVidBuf);
    printf("hVidBufSize: %d\n",(int)Buffer_getSize(hVidBuf));

    if (fifoRet < 0) {
        ERR("Failed to get buffer from video thread\n");
        cleanup(THREAD_FAILURE);
    }

    /* Did the capture thread flush the fifo? */
    if (fifoRet == Dmai_EFLUSH) {
        cleanup(THREAD_SUCCESS);
    }

    if (!envp->passThrough) {
        /*
         * Encode and decode the buffer from the capture thread and
         * send any display buffers to the display thread.
         */
        //ret = encodedecode(hVe, hVd, hVidBuf, hEncBuf, hOutBuf, envp->hDisplayInFifo);
	printf("encodedecode 1.\n");
        ret = encodedecode(hVe, hVd, hVidBuf, hEncBuf, envp->hDisplayInFifo,dirName);
        if (ret < 0) {
            cleanup(THREAD_FAILURE);
        }
    }
    else {
        /* Send the buffer through to the display thread unmodified */
        if (Fifo_put(envp->hDisplayInFifo, hVidBuf) < 0) {
            ERR("Failed to send buffer to display thread\n");
            cleanup(THREAD_FAILURE);
        }
    }
    //printf("11111111111111111111111111111111\n");
    /* Prime the display thread */
    for (bufIdx=0; bufIdx < numBufs - CAPTURE_PIPE_SIZE  - 1; bufIdx++) {
        if (ret != Dmai_EFIRSTFIELD) {
            /* Get a video buffer from the capture thread */
            fifoRet = Fifo_get(envp->hCaptureOutFifo, &hVidBuf);

            if (fifoRet < 0) {
                ERR("Failed to get buffer from video thread\n");
                cleanup(THREAD_FAILURE);
            }

            /* Did the capture thread flush the fifo? */
            if (fifoRet == Dmai_EFLUSH) {
                cleanup(THREAD_SUCCESS);
            }
        }
    }
    //printf("2222222222222222222222222222222222222\n");
    /* Release the display thread, it is now fully primed */
    //Pause_off(envp->hPausePrime);

cleanup:
    /* Make sure the other threads aren't waiting for us */
    Rendezvous_force(envp->hRendezvousInit);
    Pause_off(envp->hPauseProcess);
    //Pause_off(envp->hPausePrime);
    Fifo_flush(envp->hDisplayInFifo);
    /* Meet up with other threads before cleaning up */
    //Rendezvous_meet(envp->hRendezvousCleanup);
    /* Clean up the thread before exiting */
    if (hEncBuf) {
        Buffer_delete(hEncBuf);
    }

    if (hVd) {
        Vdec_delete(hVd);
    }

    if (hVe) {
        Venc_delete(hVe);
    }

    if (hEngine) {
        Engine_close(hEngine);
    }

    if (hBufTab) {
        BufTab_delete(hBufTab);
    }
    printf("end of videoThrFxn().\n");
    exit(0);
    return status;
}

